package com.joinway.framework.core.utils;

import java.util.concurrent.ConcurrentHashMap;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.jdbc.datasource.DataSourceUtils;

import com.joinway.framework.data.jdbc.repository.TableRepository;

//@Component("frameworkBeanFactory")
@Deprecated
public class FrameworkBeanFactory implements ApplicationContextAware {
	private final static Logger log = LoggerFactory.getLogger(FrameworkBeanFactory.class);
			
	private final static ConcurrentHashMap<Class<TableRepository>, TableRepository> holder = new ConcurrentHashMap<>();
	private static TableRepository repository;
	
	private static ApplicationContext ctx;
	
	private @Autowired DataSource dataSource;

	@SuppressWarnings("unchecked")
	public static<T> T getBean(Class<T> type){
		T bean = null;
		
		try{
			bean = ctx.getBean(type);
		}catch(Exception e){
			try{
				FrameworkBeanFactory factory = ctx.getBean(FrameworkBeanFactory.class);
				
				if(type == TableRepository.class){
					bean = (T)factory.getTableRepository();
				}
			}catch(Exception ee){
				log.warn("get bean " + type.getCanonicalName() + " failed", e.getMessage());
			}
		}
		
		return bean;
	}

	private TableRepository getTableRepository(){
		if(!holder.containsKey(TableRepository.class)){
			repository = new TableRepository(DataSourceUtils.getConnection(dataSource));
			holder.putIfAbsent(TableRepository.class, repository);
		}
		
		return repository;
	}
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		ctx = applicationContext;
	}

}
